extends CharacterBody2D
class_name Enemy



@export var dying_duration = 2.0
@export var cur_speed =150
@export var health:int = 100

var is_vulnerable = false
var is_dying =false
var dying_timer =0.0
var is_mouse_over = false  # 标记鼠标是否在角色区域

@onready var health_sta = $Health
@onready var ai=$AI
@onready var sprite =$Sprite2D
@onready var weapon = $Weapon


func _ready():
	ai.initialize(self,weapon)
	health_sta._set_health(health)
	
func _physics_process(delta):
	
	# 濒死状态：停止移动，更新计时器
	if is_dying:
		dying_timer += delta
		if Input.is_action_pressed("execute"):
			if is_mouse_over:
				execute(self)
		# 濒死时间超时：自然死亡
		if dying_timer >= dying_duration:
			die_naturally()

func update_apppearance():
	var hp_ratio = health_sta.cur_health / health_sta.max_health
	sprite.modulate = Color(1, 1 - (1 - hp_ratio) * 0.8, 1 - (1 - hp_ratio) * 0.8)

func handle_hit(cur_damage):
	if health_sta.cur_health<=0:
		return
	#数据处理
	health_sta.cur_health -=cur_damage
	health_sta.cur_health=max(health_sta.cur_health, 0)
	#濒死处决处理
	if health_sta.cur_health <= health_sta.max_health * 0.3 and not is_dying:
		enter_dying_state()
	#print(health_sta.cur_health)
	if health_sta.cur_health <= 0:
		queue_free()

func enter_dying_state():
#	print("entry dying===============")
	is_dying = true
	is_vulnerable =true
	update_apppearance()
	
	velocity = Vector2.ZERO
	
	dying_timer = 0.0
	
func execute(enemy):
	is_dying =false
	is_vulnerable =false
	#print("发送信号==============")
	#print(enemy)
	GlobalSignals.emit_signal("being_executed",enemy)

func die_naturally():
	queue_free()

func executed():
	queue_free()

func _on_area_2d_mouse_entered():
	is_mouse_over = true

func _on_area_2d_mouse_exited():	
	is_mouse_over = false
	
func rotate_toward(location:Vector2):
	rotation = lerp(rotation,global_position.direction_to(location).angle(),0.1)
	
func velocity_toward(location: Vector2):
	return global_position.direction_to(location)* cur_speed
